package cn.yuemouren.security.browser;

import cn.yuemouren.security.core.entity.SimpleResponse;
import cn.yuemouren.security.core.social.support.SocialUserInfo;
import cn.yuemouren.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Timi
 * @Description: TODO
 * @Date: 2020/6/4 8:47
 */
@RestController
public class BrowserSecurityController {

    private Logger log = LoggerFactory.getLogger(getClass());
    //请求缓存
    private RequestCache requestCache = new HttpSessionRequestCache();
    //重定向策略
    private RedirectStrategy strategy = new DefaultRedirectStrategy();
    //配置文件获取登录页
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    /**
     * 当需要认证跳转至这里
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requiredAuthentication(HttpServletRequest request, HttpServletResponse response){
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if(null != savedRequest){
            String redirectUrl = savedRequest.getRedirectUrl();
            log.info("请求跳转的路径是："+redirectUrl);
            if(StringUtils.endsWithIgnoreCase(redirectUrl,".html")){
                try {
                    strategy.sendRedirect(request,response, securityProperties.getBrowser().getLoginPage());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new SimpleResponse("访问服务需要认证，请引导用户去登录页");
    }

    @GetMapping("/social/user")
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request){
        SocialUserInfo userInfo = new SocialUserInfo();
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        userInfo.setProviderId(connection.getKey().getProviderId());
        userInfo.setUserProviderId(connection.getKey().getProviderUserId());
        userInfo.setNickname(connection.getDisplayName());
        userInfo.setHeadImage(connection.getImageUrl());
        return userInfo;
    }
}
